import { useEffect, useMemo } from 'react';
import { Common, PageCommon, WebSocket2 } from 'UtilsCommon';
import useProcessData from './useProcessData';
import useConnectDataAction from './useConnectDataAction';
import useDvaData from './useDvaData';
import usePageAxis from './usePageAxis';
import useGetPageConfig from './useGetPageConfig';
import useGetUser from './useGetUser';
import aopc from 'aopc';

export default (name, props, mapStateToProps, init, dataActionOptions) => {
  const id = useMemo(() => {
    PageCommon.clear();
    return Common.createGuid();
  }, []);

  const pageName = dataActionOptions && dataActionOptions.name ? dataActionOptions.name : name;
  // 1、 使用dva数据
  const [dispatch, dispatchAction, setActionState, getActionState, state] = useDvaData(props.app, mapStateToProps);

  // 2、 使用链接数据行为
  const [invokeDataAction, actionTypes, actionData] = useConnectDataAction(dispatch, dispatchAction, setActionState, name, dataActionOptions);

  // 3、 使用处理数据
  const [getStateValue] = useProcessData(id, state, props);

  // 4、 使用获取页面配置
  const pageConfig = useGetPageConfig(pageName, props.id || '', dispatchAction);

  // 5、 使用页线，作用贯穿整个流程
  const pageAxis = usePageAxis(id, pageName, pageConfig, invokeDataAction, actionTypes, dispatch, props,
    dispatchAction, setActionState, getActionState, getStateValue, init
  );

  const expandPageAction = aopc.useExpandPageAction(pageAxis);

  const user = useGetUser(pageAxis, expandPageAction);

  const expandPageAction2 = aopc.useExpandPageAction2(pageAxis, user);

  // 7、 接收行为数据
  useEffect(() => {
    pageAxis && pageAxis.receiveActionData(actionData);
  }, [pageAxis, actionData]);

  // 8、扩展接收数据
  useEffect(() => {
    pageAxis && pageAxis.receiveState && pageAxis.receiveState(state);
  }, [pageAxis, state]);

  useEffect(() => {
    if (pageAxis && expandPageAction && expandPageAction2 && user) {
      pageAxis.addPageAccessStatistics();
      pageAxis.componentDidmount && pageAxis.componentDidmount();
    }
  }, [pageAxis, expandPageAction, expandPageAction2, user]);

  if (pageAxis) {
    if (!window.loginUser) {
      const us = Common.getStorage('loginUserInfo');
      if (us) window.loginUser = JSON.parse(us);
    }
  }

  if (pageAxis === null || expandPageAction === null || expandPageAction2 === null || !user) return null;

  if (user && user.MeetingRoomId && !pageAxis.isBranchPage && !pageAxis.isComponentPage && !pageAxis.webSocket) {
    pageAxis.webSocket = WebSocket2.getWebSocket(user.MeetingRoomId, pageAxis.receiveFunctions);
  }

  if (pageAxis.setInit && !pageAxis.isSetInit) {
    pageAxis.setInit();
    pageAxis.isSetInit = true;
  }

  return pageAxis;
};
